package com.fyf.game.net;

import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;
import org.je.log.JLog;

/**
 * @author fanyifeng 2013-1-8 下午5:28:01
 */
public class SelectManager
{
	private Selector			sel;
	private volatile boolean	needWakeup;

	public SelectManager() {
		sel = NioUtil.createSelector();
	}

	public void setNeedWakeup() {
		needWakeup = true;
	}

	public int select() {
		try {
			return sel.select(100);
		} catch (Exception ex) {
			JLog.error(ex);
			return -1;
		} finally {
			needWakeup = false;
		}
	}

	public void wakeup() {
		if (needWakeup) {
			try {
				sel.wakeup();
			} catch (Exception ex) {}
		}
	}

	public Iterator<SelectionKey> keys() {
		return sel.selectedKeys().iterator();
	}

	/**
	 * @param channel
	 * @param ops
	 * @return key
	 */
	public SelectionKey register(SelectableChannel channel, int ops) {
		try {
			return channel.register(sel, ops);
		} catch (ClosedChannelException ex) {
			throw new RuntimeException(ex);
		}
	}

	public void close() {
		try {
			sel.close();
		} catch (Exception ex) {
			JLog.error(ex);
		}
	}
}
